package com.eurobcoin.controller;

import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.eurobcoin.EurobcoinTable;
import com.eurobcoin.dao.mapper.FilipidesEmailMapper;
import com.eurobcoin.dao.model.FilipidesEmail;
import com.eurobcoin.dao.model.FilipidesEmailExample;
import com.eurobcoin.helper.TextsHelper;
import com.eurobcoin.manager.DAOManager;
import com.eurobcoin.model.FilipidesUserModel;
import com.eurobcoin.worker.MailWorker;

@Controller
@RequestMapping("/filipides")
@SessionAttributes({"filipidesUsuarios"})
public class FilipidesController {

	private static final Logger logger = LoggerFactory.getLogger(FilipidesController.class);
	
	private static final String FILIPIDES_USUARIOS_VIEW = "filipides_usuarios";
	
	@Autowired
	private DAOManager daoManager;
	
	@Autowired
	private MailWorker mailWorker;
	
	@ModelAttribute("filipidesUsuarios")
	public EurobcoinTable createFilipidesUsuarios() {
		return new EurobcoinTable();
	}
	
	@RequestMapping(value="/resend_invitation.html", method=RequestMethod.GET)
	public ModelAndView resendInvitation(
			@ModelAttribute(value="filipidesUsuarios") EurobcoinTable filipidesUsuarios,
			@RequestParam(value="id") int id) throws Exception {
		
		ModelAndView ret = new ModelAndView(FILIPIDES_USUARIOS_VIEW);
		
		SqlSession sqlSession = this.daoManager.openSession();
		
		FilipidesEmailMapper mapper = sqlSession.getMapper(FilipidesEmailMapper.class);
		FilipidesEmail email = mapper.selectByPrimaryKey(id);
		
		// TODO: Correjir
		Locale locale = new Locale("es", "ES");
		
		String urlTemplate = TextsHelper.getStaticText(
				sqlSession, 
				TextsHelper.TXT_LBL_REG_USR_CONFIRM_URL, 
				locale.getLanguage());
		String emailBodyTemplate = TextsHelper.getStaticText(
				sqlSession, 
				TextsHelper.TXT_LBL_REG_USR_EMAIL_BODY, 
				locale.getLanguage());

		String emailSubject = TextsHelper.getStaticText(
				sqlSession, 
				TextsHelper.TXT_LBL_REG_USR_EMAIL_SUBJECT, 
				locale.getLanguage());

		String url = MessageFormat.format(urlTemplate, email.getFil_hash());
		String emailBody = MessageFormat.format(emailBodyTemplate, url);
		
		this.mailWorker.queueEmail(
				email.getFil_email(), 
				email.getFil_email(), 
				emailSubject, 
				emailBody, 
				sqlSession);
		
		sqlSession.commit();
		sqlSession.close();
		
		ret.addObject("message", "El correo se ha enviado con éxito.");
		
		return ret;
		
	}
	
	@RequestMapping(value="/delete.html", method=RequestMethod.GET)
	public ModelAndView deleteFilipidesUser(
			@ModelAttribute(value="filipidesUsuarios") EurobcoinTable filipidesUsuarios,
			@RequestParam(value="id") int id) throws Exception {
		
		ModelAndView ret = new ModelAndView(FILIPIDES_USUARIOS_VIEW);
		
		SqlSession sqlSession = this.daoManager.openSession();
		
		FilipidesEmailMapper mapper = sqlSession.getMapper(FilipidesEmailMapper.class);
		mapper.deleteByPrimaryKey(id);
		
		this.loadUsers(sqlSession, filipidesUsuarios, filipidesUsuarios.getSelectedPage());
		if(filipidesUsuarios.getSelectedPage() > 1 && filipidesUsuarios.getRows().size() == 0) {
			this.loadUsers(sqlSession, filipidesUsuarios, filipidesUsuarios.getSelectedPage() - 1);
		}
		
		sqlSession.commit();
		sqlSession.close();
		
		ret.addObject("message", "El usuario ha sido eliminado con éxito.");
		
		return ret;
		
	}
	
	@RequestMapping(value="/usuarios.html", method=RequestMethod.GET)
	public ModelAndView showUsuarios(
			@ModelAttribute(value="filipidesUsuarios") EurobcoinTable filipidesUsuarios, 
			@RequestParam(value="page", required=false) Integer page) throws Exception {
		
		if(page == null)
			page = 1;
		
		ModelAndView ret = new ModelAndView(FILIPIDES_USUARIOS_VIEW);
		
		SqlSession sqlSession = this.daoManager.openSession();
		
		this.loadUsers(sqlSession, filipidesUsuarios, page);
		
		sqlSession.close();
		
		return ret;
		
	}
	
	private void loadUsers(
			SqlSession sqlSession, 
			EurobcoinTable filipidesUsuarios, 
			int page) throws Exception {
		
		filipidesUsuarios.clearRows();
		
		FilipidesEmailMapper mapper = sqlSession.getMapper(FilipidesEmailMapper.class);
		FilipidesEmailExample example = new FilipidesEmailExample();
		example.setOrderByClause("fil_id ASC");
		
		int offset = (page - 1) * EurobcoinTable.ROWS_PER_PAGE;
		RowBounds rowBounds = new RowBounds(offset, EurobcoinTable.ROWS_PER_PAGE);
		
		List<FilipidesEmail> emailList = mapper.selectByExampleWithRowbounds(example, rowBounds);
				
		// cuento todos los elementos
		int count = mapper.countByExample(example);

		filipidesUsuarios.setTotalElements(count);
		filipidesUsuarios.setSelectedPage(page);
		
		for(FilipidesEmail filipidesEmail : emailList) {
			
			FilipidesUserModel fum = new FilipidesUserModel();
			fum.setId(filipidesEmail.getFil_id());
			fum.setConfirmed(filipidesEmail.getFil_confirmed().equals("Y"));
			fum.setEmail(filipidesEmail.getFil_email());
			fum.setHash(filipidesEmail.getFil_hash());
			
			fum.setDeleteActionAllowed(true);
			
			if(!fum.isConfirmed())
				fum.setResendEmailActionAllowed(true);
			
			filipidesUsuarios.addRow(fum);
		}
		
	}
	
}
